# -*- coding: utf-8 -*-
# @Time : 2022/2/7 11:46

from Common.mysql import db
from Common.public_method import utc_8
from src.ApiTest.ProjectConfig.Database.mysqlConfig_database import MysqlConfig, MysqlConfigSchema
from sqlalchemy.exc import SQLAlchemyError
from Common.yaml_method import YamlMethod


class UpdateMysqlInfo:
    """
    更新数据库信息接口
    """

    @staticmethod
    def update_mysql_info(database_type, database_name, config_id, config_name, project_id, project_name, environment,
                          host, port, user, password, update_user, is_jump=None, jump_port=None, jump_host=None,
                          jump_name=None):
        """
        更新数据库配置信息
        :param database_type: 数据库类型
        :param database_name: 数据库名
        :param config_id: 配置ID
        :param config_name: 配置名称
        :param project_id: 项目ID
        :param project_name: 项目名称
        :param environment: 运行环境
        :param host: host
        :param port: 端口号
        :param user: 用户名
        :param password: 密码
        :param update_user: 更新人
        :param is_jump: 是否需要跳板机
        :param jump_port: 跳板机端口
        :param jump_host: 跳板机IP
        :param jump_name: 跳板机用户名
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        update_time = utc_8()

        info = MysqlConfig.query.filter_by(id=config_id).first()

        if info:
            info.databaseType = database_type
            info.databaseName = database_name
            info.configName = config_name
            info.projectId = project_id
            info.projectName = project_name
            info.environment = environment
            info.host = host
            info.port = port
            info.user = user
            info.password = password
            info.isJump = is_jump
            info.jumpPort = jump_port
            info.jumpHost = jump_host
            info.jumpName = jump_name
            info.update_time = update_time
            info.update_user = update_user

            try:
                db.session.commit()
            except SQLAlchemyError:
                db.session.rollback()
                res = {
                    'code': code[6],
                    'data': [],
                    'message': '数据库信息更新失败'
                }
                return res

            res = {
                'code': code[0],
                'data': [],
                'message': '数据库信息更新成功'
            }
            return res
        else:
            res = {
                'code': code[3],
                'data': [],
                'message': '数据库信息不存在'
            }
            return res
